package img

import (
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"os"
)

type DeleteIMG struct {
	beego.Controller
}

func (c *DeleteIMG) DeleteIMG() {

	defer func() {
		c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/img/PostIMG"
	var err error
	log := &error2.Log{}
	mes := &error2.Mes{}

	sessionUnkown := c.Ctx.Request.Header["Session"]
	//fmt.Println([]byte(c.GetString("activity")))

	if len(sessionUnkown) == 0 {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("sessionNull"), addr, "sessionNull")
		return
	}
	session := sessionUnkown[0]
	if session == "" {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("sessionNull"), addr, "sessionNull")
		return
	}

	ses, err := session2.FindSession(session)
	//fmt.Println(ses.Admin)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	} else if ses == nil {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "404", "session过期")
		return
	} else if ses.Admin == nil {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "400", "未登录")
		return
	}
	if ses.Admin.Privilege != 1 && ses.Admin.ActivityManagement != 1 {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "400", "无权限")
		return
	}

	url := c.GetString("url")
	if url == "" {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "401", "urlNull")
		return
	}
	err = os.Remove("." + url)

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return

	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}
